package com.github.shiqiyue.myadmin.service;

import javax.annotation.PostConstruct;

import org.owasp.validator.html.AntiSamy;
import org.owasp.validator.html.CleanResults;
import org.owasp.validator.html.Policy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

/***
 * xss 保护服务
 * 
 * @author wwy shiqiyue.github.com
 *
 */
@Service
public class XssProtectService {
	
	private AntiSamy antiSamy;
	
	private Policy policy;
	
	private static final Logger log = LoggerFactory.getLogger(XssProtectService.class);
	
	@PostConstruct
	public void init() {
		antiSamy = new AntiSamy();
		try {
			ClassPathResource resource = new ClassPathResource("/antisamy.xml");
			policy = Policy.getInstance(resource.getInputStream());
		} catch (Exception e) {
			log.error("初始化xss规则失败", e);
		}
	}
	
	public String cleanXss(String input) {
		String result = null;
		try {
			CleanResults cleanResults = antiSamy.scan(input, policy);
			result = cleanResults.getCleanHTML();
		} catch (Exception e) {
			log.error("文本清理xss失败", e);
		}
		return result;
	}
	
}
